package com.coszero.utilslibrary.encryption;

import android.annotation.TargetApi;
import android.os.Build;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * Desc： MD5加解密操作
 * <p>
 * @author ： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/8/16 15:52
 * @version 1
 */
public class MD5Utils {
    /**
     * 小写32位md5加密
     *
     * @param str
     * @return
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getMD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        byte[] md5Bytes = new byte[0];
        md5Bytes = md5.digest(str.getBytes(StandardCharsets.UTF_8));
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
